package com.csust.cg.mongodb.inteceptor;

import com.csust.cg.mongodb.domain.HttpStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author chenguang
 */
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("u-token");
        if (StringUtils.isBlank(token)) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print("{\"code\":" + HttpStatus.UNAUTHORIZED + ",\"msg\":\"无权限操作！\"}");
            return false;
        }
        Object sessionToken = request.getSession().getAttribute("token");
        if (sessionToken == null) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print("{\"code\":" + HttpStatus.FORBIDDEN + ",\"msg\":\"Token失效，请重新登陆！\"}");
            return false;
        }
        if (!sessionToken.toString().equals(token)) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print("{\"code\":" + HttpStatus.UNAUTHORIZED + ",\"msg\":\"无权限操作！\"}");
            return false;
        }
        return true;
    }
}
